package com.ftg.learn.chapter05;

/**
 * 学习一下树
 *
 * @author 布衣
 */
public class LearnTree<E> {

    //特殊的数据结构  :
    private class TreeNode<E> {
        private TreeNode<E> left;
        private E data;
        private TreeNode<E> right;
    }

    private TreeNode<E> root;

    public void insert(E data, TreeNode<E> parent, boolean isLeft) {
        if (root == null) {
            root = new TreeNode<>();
            root.data = data;
            return ;
        }

        if(parent == null){
            throw new RuntimeException("父节点不能为空");
        }

        TreeNode<E> temp = new TreeNode<>();
        temp.data = data;
        if (isLeft) {
            parent.left = temp;
        } else {
            parent.right = temp;
        }
    }

    /**
     * 先根遍历  【1，2，3，4，5，7】
     * @param node
     */
    public void forEach1(TreeNode<E> root){
        if(root == null){
            return ;
        }
        System.out.println(root.data);
        forEach1(root.left);
        forEach1(root.right);
    }

    /**
     * 中根
     * @param root
     */
    public void forEach2(TreeNode<E> root){
        if(root == null){
            return ;
        }
        forEach2(root.left);
        System.out.println(root.data);
        forEach2(root.right);
    }

    /**
     * 后根
     * @param root
     */
    public void forEach3(TreeNode<E> root){
        if(root == null){
            return ;
        }
        forEach3(root.left);
        forEach3(root.right);
        System.out.println(root.data);
    }


    //bfs dfs []
    private TreeNode<E> getNodeByLevel(int level,int index){
        return null;
    }
    public static void main(String[] args) {
        LearnTree<Integer> learnTree = new LearnTree<>();
        learnTree.insert(45, null, true);
        learnTree.insert(46, learnTree.root, true);
        learnTree.insert(78, learnTree.root, false);
        learnTree.insert(79, learnTree.root.left, false);
        learnTree.insert(77, learnTree.root.left, true);


//        learnTree.forEach1(learnTree.root);
        learnTree.forEach2(learnTree.root);
    }



}
